<?php

class Pldkp_View_Helper_IsUserAllowed extends Zend_View_Helper_Abstract
{
    protected static $_acl = null;
    protected static $_request = null;
    
    public function __construct()
    {
        if (self::$_acl === null) {
            $registry = Zend_Registry::getInstance();
            if (!$registry->isRegistered('acl')) {
                throw new Exception('Acl is not in registry under key: \'acl\'');
            }
            self::$_acl = Zend_Registry::getInstance()->acl;
            if (!self::$_acl || !is_callable(array(self::$_acl, 'isUserAllowed'))) {
                throw new Exception('Acl is null, or does not implement isUserAllowed');
            }
        }
        
        self::$_request = Zend_Controller_Front::getInstance()->getRequest();
    }
    
    /**
     * 
     * @param array $url
     * @return array
     */
    protected function prepareUrl(array $url = array())
    {
        if (!isset($url['module'])) {
            $url['module'] = self::$_request->getModuleName();
        }
        if (!isset($url['controller'])) {
            $url['controller'] = self::$_request->getControllerName();
        }
        if (!isset($url['action'])) {
            $url['action'] = self::$_request->getActionName();
        }
        
        return $url;
    }
    
    
    public function isUserAllowed(array $url = array())
    {
        $url = $this->prepareUrl($url);
        
        if (!self::$_acl->isUserAllowed($url['module'], $url['controller'], $url['action'])) {
            return false;
        }
        
        return true;
    }
}
